package bma.common.thrift.common;

import java.lang.reflect.Constructor;

import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;

import bma.common.langutil.core.ExceptionUtil;
import bma.common.thrift.ThriftClient;

/**
 * 
 * @author guanzhong
 * 
 */
public class ThriftClientCommon implements ThriftClient {

	protected TTransport transport;
	protected TProtocol protocol;

	public ThriftClientCommon(TTransport transport, TProtocol protocol) {
		super();
		this.transport = transport;
		this.protocol = protocol;
	}

	public TTransport getTransport() {
		return transport;
	}

	public void setTransport(TTransport transport) {
		this.transport = transport;
	}

	public TProtocol getProtocol() {
		return protocol;
	}

	public void setProtocol(TProtocol protocol) {
		this.protocol = protocol;
	}

	@Override
	public <TYPE extends TServiceClient> TYPE createObject(Class<TYPE> cls) {
		try {
			Constructor<TYPE> c = cls.getConstructor(TProtocol.class);
			return c.newInstance(getProtocol());
		} catch (Exception e) {
			throw ExceptionUtil.throwRuntime(e);
		}
	}

	public void close() {
		if (this.transport != null) {
			this.transport.close();
			this.transport = null;
			this.protocol = null;
		}
	}
}
